package org.monkey.feign.plugin.handler;


import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.monkey.common.constant.entity.ErrorResultEnum;
import org.monkey.common.constant.entity.Result;
import org.monkey.common.constant.exception.BaseException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author:JZ
 * @date:2020/5/16
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

  /**
   * 系统异常处理器
   *
   * @param throwable
   * @param request
   * @return
   */
  @ExceptionHandler(Throwable.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)   // 指定http状态码，如果不指定为非2xx，feign不会抛出异常
  public Result systemExceptionHandler(Throwable throwable, HttpServletRequest request) {
    log.error("URL：{} ,system error", request.getRequestURI(), throwable);
    BaseException baseException = new BaseException(ErrorResultEnum.SYSTEM_ERROR, throwable);
    return Result.error(baseException);
  }

  /**
   * 自定义异常处理器
   */
  @ExceptionHandler(BaseException.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)   // 指定http状态码，如果不指定为非2xx，feign不会抛出异常
  public Result baseExceptionHandler(BaseException baseException, HttpServletRequest request) {
    log.warn("URL：{} ,service error", request.getRequestURI());
    return Result.error(baseException);
  }

}
